Project: Identify Customer Segments

In this project, you will apply unsupervised learning techniques to identify segments of the population that form the core customer base for a mail-order sales company in Germany. These segments can then be used to direct marketing campaigns towards audiences that will have the highest expected rate of returns. The data that you will use has been provided by our partners at Bertelsmann Arvato Analytics, and represents a real-life data science task.

This notebook will help you complete this task by providing a framework within which you will perform your analysis steps. In each step of the project, you will see some text describing the subtask that you will perform, followed by one or more code cells for you to complete your work. Feel free to add additional code and markdown cells as you go along so that you can explore everything in precise chunks. The code cells provided in the base template will outline only the major tasks, and will usually not be enough to cover all of the minor tasks that comprise it.

It should be noted that while there will be precise guidelines on how you should handle certain tasks in the project, there will also be places where an exact specification is not provided. There will be times in the project where you will need to make and justify your own decisions on how to treat the data. These are places where there may not be only one way to handle the data. In real-life tasks, there may be many valid ways to approach an analysis task. One of the most important things you can do is clearly document your approach so that other scientists can understand the decisions you've made.

At the end of most sections, there will be a Markdown cell labeled Discussion. In these cells, you will report your findings for the completed section, as well as document the decisions that you made in your approach to each subtask. Your project will be evaluated not just on the code used to complete the tasks outlined, but also your communication about your observations and conclusions at each stage.

In [1]:
# import libraries here; add more as necessary
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

import plotly
import plotly.graph_objects as go
import re
import math
import pickle 

from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans

import time

# magic word for producing visualizations in notebook
%matplotlib inline

'''
Import note: The classroom currently uses sklearn version 0.19.
If you need to use an imputer, it is available in sklearn.preprocessing.Imputer,
instead of sklearn.impute as in newer versions of sklearn.
'''
Out[1]:
'\nImport note: The classroom currently uses sklearn version 0.19.\nIf you need to use an imputer, it is available in sklearn.preprocessing.Imputer,\ninstead of sklearn.impute as in newer versions of sklearn.\n'

Step 0: Load the Data

There are four files associated with this project (not including this one):

  • Udacity_AZDIAS_Subset.csv: Demographics data for the general population of Germany; 891211 persons (rows) x 85 features (columns).
  • Udacity_CUSTOMERS_Subset.csv: Demographics data for customers of a mail-order company; 191652 persons (rows) x 85 features (columns).
  • Data_Dictionary.md: Detailed information file about the features in the provided datasets.
  • AZDIAS_Feature_Summary.csv: Summary of feature attributes for demographics data; 85 features (rows) x 4 columns

Each row of the demographics files represents a single person, but also includes information outside of individuals, including information about their household, building, and neighborhood. You will use this information to cluster the general population into groups with similar demographic properties. Then, you will see how the people in the customers dataset fit into those created clusters. The hope here is that certain clusters are over-represented in the customers data, as compared to the general population; those over-represented clusters will be assumed to be part of the core userbase. This information can then be used for further applications, such as targeting for a marketing campaign.

To start off with, load in the demographics data for the general population into a pandas DataFrame, and do the same for the feature attributes summary. Note for all of the .csv data files in this project: they're semicolon (;) delimited, so you'll need an additional argument in your read_csv() call to read in the data properly. Also, considering the size of the main dataset, it may take some time for it to load completely.

Once the dataset is loaded, it's recommended that you take a little bit of time just browsing the general structure of the dataset and feature summary file. You'll be getting deep into the innards of the cleaning in the first major step of the project, so gaining some general familiarity can help you get your bearings.

In [2]:
# Load in the general demographics data.
azdias = pd.read_csv('Udacity_AZDIAS_Subset.csv', sep=";")
# Load in the feature summary file.
feat_info = pd.read_csv('AZDIAS_Feature_Summary.csv', sep = ";")
In [3]:
# Check the structure of the data after it's loaded (e.g. print the number of
# rows and columns, print the first few rows).
display(azdias.head(5))
display(feat_info.head())
AGER_TYP ALTERSKATEGORIE_GROB ANREDE_KZ CJT_GESAMTTYP FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER ... PLZ8_ANTG1 PLZ8_ANTG2 PLZ8_ANTG3 PLZ8_ANTG4 PLZ8_BAUMAX PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB
0 -1 2 1 2.0 3 4 3 5 5 3 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
1 -1 1 2 5.0 1 5 2 5 4 5 ... 2.0 3.0 2.0 1.0 1.0 5.0 4.0 3.0 5.0 4.0
2 -1 3 2 3.0 1 4 1 2 3 5 ... 3.0 3.0 1.0 0.0 1.0 4.0 4.0 3.0 5.0 2.0
3 2 4 2 2.0 4 2 5 2 1 2 ... 2.0 2.0 2.0 0.0 1.0 3.0 4.0 2.0 3.0 3.0
4 -1 3 1 5.0 4 3 4 1 3 2 ... 2.0 4.0 2.0 1.0 2.0 3.0 3.0 4.0 6.0 5.0

5 rows × 85 columns

attribute information_level type missing_or_unknown
0 AGER_TYP person categorical [-1,0]
1 ALTERSKATEGORIE_GROB person ordinal [-1,0,9]
2 ANREDE_KZ person categorical [-1,0]
3 CJT_GESAMTTYP person categorical [0]
4 FINANZ_MINIMALIST person ordinal [-1]
In [4]:
azdias.describe()
Out[4]:
AGER_TYP ALTERSKATEGORIE_GROB ANREDE_KZ CJT_GESAMTTYP FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER ... PLZ8_ANTG1 PLZ8_ANTG2 PLZ8_ANTG3 PLZ8_ANTG4 PLZ8_BAUMAX PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB
count 891221.000000 891221.000000 891221.000000 886367.000000 891221.000000 891221.000000 891221.000000 891221.000000 891221.000000 891221.000000 ... 774706.000000 774706.000000 774706.000000 774706.000000 774706.000000 774706.000000 774706.000000 794005.000000 794005.000000 794005.00000
mean -0.358435 2.777398 1.522098 3.632838 3.074528 2.821039 3.401106 3.033328 2.874167 3.075121 ... 2.253330 2.801858 1.595426 0.699166 1.943913 3.612821 3.381087 3.167854 5.293002 3.07222
std 1.198724 1.068775 0.499512 1.595021 1.321055 1.464749 1.322134 1.529603 1.486731 1.353248 ... 0.972008 0.920309 0.986736 0.727137 1.459654 0.973967 1.111598 1.002376 2.303739 1.36298
min -1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 ... 0.000000 0.000000 0.000000 0.000000 1.000000 1.000000 1.000000 1.000000 0.000000 1.00000
25% -1.000000 2.000000 1.000000 2.000000 2.000000 1.000000 3.000000 2.000000 2.000000 2.000000 ... 1.000000 2.000000 1.000000 0.000000 1.000000 3.000000 3.000000 3.000000 4.000000 2.00000
50% -1.000000 3.000000 2.000000 4.000000 3.000000 3.000000 3.000000 3.000000 3.000000 3.000000 ... 2.000000 3.000000 2.000000 1.000000 1.000000 4.000000 3.000000 3.000000 5.000000 3.00000
75% -1.000000 4.000000 2.000000 5.000000 4.000000 4.000000 5.000000 5.000000 4.000000 4.000000 ... 3.000000 3.000000 2.000000 1.000000 3.000000 4.000000 4.000000 4.000000 7.000000 4.00000
max 3.000000 9.000000 2.000000 6.000000 5.000000 5.000000 5.000000 5.000000 5.000000 5.000000 ... 4.000000 4.000000 3.000000 2.000000 5.000000 5.000000 5.000000 9.000000 9.000000 9.00000

8 rows × 81 columns

In [5]:
nulls_count = azdias.isnull().sum()
nulls_count_df = pd.DataFrame(nulls_count).reset_index().rename(columns={'index':'feature',0:'count'})
nulls_count_df['percentage'] = nulls_count_df['count']/azdias.shape[0]
nulls_count_df.head(4)

# Plot missing values

fig = go.Figure(data = 
                (
                    go.Bar(x=nulls_count_df['feature'], 
                           y=nulls_count_df['percentage'].sort_values(ascending = False),
                           marker_color = '#ABDDDE',
                           marker_line_width = 1,
                           marker_line_color = 'black'
                          )
                ),
                  
                layout = go.Layout(bargap = 0.25,
                                   title = {'text':'Sampling distribution - means', 'x': 0.5},
                                   xaxis_title="Features",
                                   yaxis_title="Proportions"
                                  ),
               )

fig.show()

Step 1: Preprocessing

Step 1.1: Assess Missing Data

The feature summary file contains a summary of properties for each demographics data column. You will use this file to help you make cleaning decisions during this stage of the project. First of all, you should assess the demographics data in terms of missing data. Pay attention to the following points as you perform your analysis, and take notes on what you observe. Make sure that you fill in the Discussion cell with your findings and decisions at the end of each step that has one!

Step 1.1.1: Convert Missing Value Codes to NaNs

The fourth column of the feature attributes summary (loaded in above as feat_info) documents the codes from the data dictionary that indicate missing or unknown data. While the file encodes this as a list (e.g. [-1,0]), this will get read in as a string object. You'll need to do a little bit of parsing to make use of it to identify and clean the data. Convert data that matches a 'missing' or 'unknown' value code into a numpy NaN value. You might want to see how much data takes on a 'missing' or 'unknown' code, and how much data is naturally missing, as a point of interest.

As one more reminder, you are encouraged to add additional cells to break up your analysis into manageable chunks.

In [6]:
# Identify missing or unknown data values and convert them to NaNs.

## Copy data 
feat_info_clean_df = feat_info.copy(deep=True)
azdias_clean_df = azdias.copy(deep=True)

feat_info_clean_df.missing_or_unknown[1]
Out[6]:
'[-1,0,9]'
In [7]:
## Define list split function

def list_split(x):
    return re.sub('[ \[ \] ]', '', x).split(",")

## Apply function to 'missing_or_unkown' column
feat_info_clean_df.missing_or_unknown = feat_info_clean_df.missing_or_unknown.apply(list_split)
feat_info_clean_df.set_index(['attribute'], inplace=True)

feat_info_clean_df.missing_or_unknown[1]
Out[7]:
['-1', '0', '9']
In [8]:
for attr in feat_info_clean_df.index:  ## For each column attribute                                 
    for x in feat_info_clean_df.loc[attr]['missing_or_unknown']: ## Extract number values in that column
        try:
            azdias_clean_df[attr].replace(int(x), np.nan, inplace=True) ## Replace those number values by NaN
        except ValueError:    
            azdias_clean_df[attr].replace(x, np.nan, inplace=True) ## Exception if value error (not int), then replace whole x with nan

azdias_clean_df.sample(n=2)
Out[8]:
AGER_TYP ALTERSKATEGORIE_GROB ANREDE_KZ CJT_GESAMTTYP FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER ... PLZ8_ANTG1 PLZ8_ANTG2 PLZ8_ANTG3 PLZ8_ANTG4 PLZ8_BAUMAX PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB
390165 NaN 1.0 2 3.0 1 5 3 5 5 2 ... 3.0 1.0 0.0 0.0 1.0 3.0 4.0 1.0 1.0 1.0
209286 NaN 3.0 2 2.0 2 3 4 5 1 3 ... 4.0 2.0 0.0 0.0 1.0 3.0 4.0 2.0 4.0 1.0

2 rows × 85 columns

Step 1.1.2: Assess Missing Data in Each Column

How much missing data is present in each column? There are a few columns that are outliers in terms of the proportion of values that are missing. You will want to use matplotlib's hist() function to visualize the distribution of missing value counts to find these columns. Identify and document these columns. While some of these columns might have justifications for keeping or re-encoding the data, for this project you should just remove them from the dataframe. (Feel free to make remarks about these outlier columns in the discussion, however!)

For the remaining features, are there any patterns in which columns have, or share, missing data?

In [9]:
# Investigate patterns in the amount of missing data in each column.

cleaned_nulls_count = azdias_clean_df.isnull().sum()
cleaned_nulls_count_df = pd.DataFrame(cleaned_nulls_count).reset_index().rename(columns={'index':'feature',0:'count'})
cleaned_nulls_count_df['percentage'] = cleaned_nulls_count_df['count']/azdias_clean_df.shape[0]
cleaned_nulls_count_df.sort_values(by = 'percentage', ascending = False, inplace=True)

fig = go.Figure(data = 
                (
                    go.Bar(x=cleaned_nulls_count_df['feature'], 
                           y=cleaned_nulls_count_df['percentage'],
                           marker_color = '#ABDDDE',
                           #text = cleaned_nulls_count_df['percentage'],
                           #texttemplate='%{text:.2s}',
                           #textposition='outside',
                           marker_line_width = 1,
                           marker_line_color = 'black'
                          )
                ),
                  
                layout = go.Layout(bargap = 0.25,
                                   title = {'text':'Missing values distribution after cleansing', 'x': 0.5},
                                   xaxis_title = "Features",
                                   yaxis_title = "Proportions"
                                  ),
               )

fig.show()
In [10]:
# Remove the outlier columns from the dataset. (You'll perform other data
# engineering tasks such as re-encoding and imputation later.)
outlier_columns = cleaned_nulls_count_df[cleaned_nulls_count_df.percentage > 0.3]['feature']
azdias_clean_df.drop(outlier_columns, axis=1, inplace=True)
display('Dropped columns are:', outlier_columns)
azdias_clean_df.shape
'Dropped columns are:'
40        TITEL_KZ
0         AGER_TYP
47    KK_KUNDENTYP
64    KBA05_BAUMAX
11     GEBURTSJAHR
43        ALTER_HH
Name: feature, dtype: object
Out[10]:
(891221, 79)

Discussion 1.1.2: Assess Missing Data in Each Column

We can see that the first column TITLE_KZ has 99%+ missing values .. I've sorted them in descending order, now we know we can stop at the ALTER_HH column where it is missing 34% of the data. You can see above the column names I've dropped.

Step 1.1.3: Assess Missing Data in Each Row

Now, you'll perform a similar assessment for the rows of the dataset. How much data is missing in each row? As with the columns, you should see some groups of points that have a very different numbers of missing values. Divide the data into two subsets: one for data points that are above some threshold for missing values, and a second subset for points below that threshold.

In order to know what to do with the outlier rows, we should see if the distribution of data values on columns that are not missing data (or are missing very little data) are similar or different between the two groups. Select at least five of these columns and compare the distribution of values.

  • You can use seaborn's countplot() function to create a bar chart of code frequencies and matplotlib's subplot() function to put bar charts for the two subplots side by side.
  • To reduce repeated code, you might want to write a function that can perform this comparison, taking as one of its arguments a column to be compared.

Depending on what you observe in your comparison, this will have implications on how you approach your conclusions later in the analysis. If the distributions of non-missing features look similar between the data with many missing values and the data with few or no missing values, then we could argue that simply dropping those points from the analysis won't present a major issue. On the other hand, if the data with many missing values looks very different from the data with few or no missing values, then we should make a note on those data as special. We'll revisit these data later on. Either way, you should continue your analysis for now using just the subset of the data with few or no missing values.

In [11]:
# How much data is missing in each row of the dataset?

cleaned_nullrows_count = azdias_clean_df.isnull().sum(axis=1)
cleaned_nullrows_count_df = pd.DataFrame(cleaned_nullrows_count).reset_index().rename(columns={'index':'row',0:'count'})
cleaned_nullrows_count_df['percentage'] = cleaned_nullrows_count_df['count']/azdias_clean_df.shape[1]
cleaned_nullrows_count_df.sort_values(['row'], inplace=True)

fig = go.Figure(data = 
                (
                    go.Histogram(x=cleaned_nullrows_count_df.query("count != 0")['count'], 
                           marker_color = '#ABDDDE',
                           #text = cleaned_nulls_count_df['percentage'],
                           #texttemplate='%{text:.2s}',
                           #textposition='outside',
                           marker_line_width = 1,
                           marker_line_color = 'black'
                          )
                ),
                  
                layout = go.Layout(bargap = 0.25,
                                   title = {'text':'Missing (row) values distribution after cleansing', 'x': 0.5},
                                   xaxis_tickmode = 'linear',
                                   xaxis_title = "column(s) count per row",
                                   yaxis_title = "frequency",
                                  ),
               )

fig.show()
In [12]:
# Write code to divide the data into two subsets based on the number of missing
# values in each row.

lesseq_than_10 = cleaned_nullrows_count_df[cleaned_nullrows_count_df['count'] <= 10]
more_than_10 = cleaned_nullrows_count_df[cleaned_nullrows_count_df['count'] > 10]

# Validation #
print('Validation: ',cleaned_nullrows_count_df.shape[0] == lesseq_than_10.shape[0] + more_than_10.shape[0])

print(lesseq_than_10.shape[0] / cleaned_nullrows_count_df.shape[0])
print(more_than_10.shape[0] / cleaned_nullrows_count_df.shape[0])
Validation:  True
0.8753754680376696
0.12462453196233034
In [13]:
import warnings
warnings.filterwarnings('ignore')

le_10_grp =  azdias_clean_df.loc[lesseq_than_10.index].isnull().sum()/azdias_clean_df.loc[lesseq_than_10.index].shape[0]
mt_10_grp = azdias_clean_df.loc[more_than_10.index].isnull().sum()/azdias_clean_df.loc[more_than_10.index].shape[0]

fig = go.Figure(layout = go.Layout(title = {'text':'Missing (row) groups prop. after cleansing', 'x': 0.5},
                                   xaxis_title = "Features",
                                   yaxis_title = "Proportions"))

fig.add_trace(go.Bar(x=le_10_grp.index,
                y=le_10_grp.values,
                name='Less than/equal 10',
                marker_color='rgb(244, 181, 189)'
                ))

fig.add_trace(go.Bar(x=mt_10_grp.index,
                y=mt_10_grp.values,
                name='More than 10',
                marker_color='#ABDDDE'
                ))

Discussion 1.1.3: Assess Missing Data in Each Row

We can observe here that 88% of the rows have less than or equal than 10 missing columns, on the other hand rows that have More than 10 missing columns account for 12%. Each legend in the plot as seen is a group.

Now, let's apply each group on each column, separetly to see if the frequency of certain rows missing that column.

We can see that the frequency for the red less than or equal than 10 group is nearly less than 1% for all the columns, while the frequency for More than 10 are mostly above 60% for more than half of the columns.

We're not going to drop rows for now, we will drop rows later in the project.

Step 1.2: Select and Re-Encode Features

Checking for missing data isn't the only way in which you can prepare a dataset for analysis. Since the unsupervised learning techniques to be used will only work on data that is encoded numerically, you need to make a few encoding changes or additional assumptions to be able to make progress. In addition, while almost all of the values in the dataset are encoded using numbers, not all of them represent numeric values. Check the third column of the feature summary (feat_info) for a summary of types of measurement.

  • For numeric and interval data, these features can be kept without changes.
  • Most of the variables in the dataset are ordinal in nature. While ordinal values may technically be non-linear in spacing, make the simplifying assumption that the ordinal variables can be treated as being interval in nature (that is, kept without any changes).
  • Special handling may be necessary for the remaining two variable types: categorical, and 'mixed'.

In the first two parts of this sub-step, you will perform an investigation of the categorical and mixed-type features and make a decision on each of them, whether you will keep, drop, or re-encode each. Then, in the last part, you will create a new data frame with only the selected and engineered columns.

Data wrangling is often the trickiest part of the data analysis process, and there's a lot of it to be done here. But stick with it: once you're done with this step, you'll be ready to get to the machine learning parts of the project!

In [14]:
# How many features are there of each data type?

print(feat_info.type.value_counts())

cat_columns = feat_info.query("type == 'categorical'")['attribute']
mixed_columns = feat_info.query("type == 'mixed'")['attribute']
ordinal        49
categorical    21
numeric         7
mixed           7
interval        1
Name: type, dtype: int64

Step 1.2.1: Re-Encode Categorical Features

For categorical data, you would ordinarily need to encode the levels as dummy variables. Depending on the number of categories, perform one of the following:

  • For binary (two-level) categoricals that take numeric values, you can keep them without needing to do anything.
  • There is one binary variable that takes on non-numeric values. For this one, you need to re-encode the values as numbers or create a dummy variable.
  • For multi-level categoricals (three or more values), you can choose to encode the values using multiple dummy variables (e.g. via OneHotEncoder), or (to keep things straightforward) just drop them from the analysis. As always, document your choices in the Discussion section.
In [15]:
# Assess categorical variables: which are binary, which are multi-level, and
# which one needs to be re-encoded?

uniq_df = pd.DataFrame(azdias_clean_df[azdias_clean_df.columns.intersection(cat_columns)].nunique(), columns=['nunique'])
type_df = pd.DataFrame(azdias_clean_df[azdias_clean_df.columns.intersection(cat_columns)].dtypes, columns=['dtype'])
cat_columns_df = pd.concat([uniq_df,type_df], axis=1).sort_values(by='nunique')
cat_columns_df
Out[15]:
nunique dtype
ANREDE_KZ 2 int64
OST_WEST_KZ 2 object
VERS_TYP 2 float64
SOHO_KZ 2 float64
GREEN_AVANTGARDE 2 int64
NATIONALITAET_KZ 3 float64
SHOPPER_TYP 4 float64
LP_STATUS_GROB 5 float64
LP_FAMILIE_GROB 5 float64
FINANZTYP 6 int64
ZABEOTYP 6 int64
CJT_GESAMTTYP 6 float64
GEBAEUDETYP 7 float64
CAMEO_DEUG_2015 9 object
LP_STATUS_FEIN 10 float64
LP_FAMILIE_FEIN 11 float64
GFK_URLAUBERTYP 12 float64
CAMEO_DEU_2015 44 object
In [16]:
## Changing that binary non-numeric column to 0 and 1 ##
azdias_clean_df.replace({'OST_WEST_KZ':{'W': 0, 'O': 1}}, inplace=True)

## Validation ##
azdias_clean_df['OST_WEST_KZ'].unique()
Out[16]:
array([nan,  0.,  1.])
In [17]:
## Dropping multivariate columns ##

azdias_clean_df.drop(cat_columns_df[cat_columns_df['nunique']>=3].index, axis=1, inplace=True)
azdias_clean_df.shape
Out[17]:
(891221, 66)

Discussion 1.2.1: Re-Encode Categorical Features

I have created a helper df that shows the number of unique values and the data type for the categorical features.

  • I have re-encoded the one-binary variable OST_WEST_KZ that takes non-numerical ['W','O'] to 0 and 1 respectively.
  • I have dropped features that host more than 3 categorical values.

Step 1.2.2: Engineer Mixed-Type Features

There are a handful of features that are marked as "mixed" in the feature summary that require special treatment in order to be included in the analysis. There are two in particular that deserve attention; the handling of the rest are up to your own choices:

  • "PRAEGENDE_JUGENDJAHRE" combines information on three dimensions: generation by decade, movement (mainstream vs. avantgarde), and nation (east vs. west). While there aren't enough levels to disentangle east from west, you should create two new variables to capture the other two dimensions: an interval-type variable for decade, and a binary variable for movement.
  • "CAMEO_INTL_2015" combines information on two axes: wealth and life stage. Break up the two-digit codes by their 'tens'-place and 'ones'-place digits into two new ordinal variables (which, for the purposes of this project, is equivalent to just treating them as their raw numeric values).
  • If you decide to keep or engineer new features around the other mixed-type features, make sure you note your steps in the Discussion section.

Be sure to check Data_Dictionary.md for the details needed to finish these tasks.

In [18]:
# Investigate "PRAEGENDE_JUGENDJAHRE" and engineer two new variables.
def get_decade(x):
    if x in (1,2):
        return 1 
    elif x in (3,4):
        return 2
    elif x in (5,6,7):
        return 3
    elif x in (8,9):
        return 4
    elif x in (10,11,12,13):
        return 5
    elif x != str:
        return x
    else:
        return 6
    
def get_region(x):
    if x in (1,2,3,4,5,8,9,14,15):
        return 1
    elif x in (6,10,11):
        return 2
    elif x in (7,12,13):
        return 3
    elif x != str:
        return x
    else: 
        return 4
    
azdias_clean_df['PRAEGENDE_JUGENDJAHRE_DECADE'] = azdias_clean_df['PRAEGENDE_JUGENDJAHRE'].apply(get_decade)
azdias_clean_df['PRAEGENDE_JUGENDJAHRE_REGION'] = azdias_clean_df['PRAEGENDE_JUGENDJAHRE'].apply(get_region)
In [19]:
# Investigate "CAMEO_INTL_2015" and engineer two new variables.

def str_range(x,y):
    return [str(i).zfill(2) for i in range(x,y+1)]

def get_wealth(x):
    if x in str_range(11,15):
        return 1
    elif x in str_range(21,25):
        return 2
    elif x in str_range(31,35):
        return 3
    elif x in str_range(41,45):
        return 4
    elif x in str_range(51,55):
        return 5
    elif x != str:
        return x
    else:
        return 6
        
    
def life_stage(x):
    if x in ('11','21','31','41','51'):
        return 1
    if x in ('12','22','32','42','52'):
        return 2
    if x in ('13','23','33','43','53'):
        return 3
    if x in ('14','24','34','44','54'):
        return 3
    if x in ('15','25','35','45','55'):
        return 4
    elif x != str:
        return x
    else:
        return 5
    
azdias_clean_df['CAMEO_INTL_2015_WEALTH'] = azdias_clean_df['CAMEO_INTL_2015'].apply(get_wealth)
azdias_clean_df['CAMEO_INTL_2015_LIFE_STAGE'] = azdias_clean_df['CAMEO_INTL_2015'].apply(life_stage)

Discussion 1.2.2: Engineer Mixed-Type Features

I have created the following features:

  1. PRAEGENDE_JUGENDJAHRE_DECADE: This is the generation by decade.
  2. PRAEGENDE_JUGENDJAHRE_REGION: This is the region where they have lived in either west, east or both.
  3. CAMEO_INTL_2015_WEALTH: This feature for wealth.
  4. CAMEO_INTL_2015_LIFE_STAGE: This is a feature for life stage.

Step 1.2.3: Complete Feature Selection

In order to finish this step up, you need to make sure that your data frame now only has the columns that you want to keep. To summarize, the dataframe should consist of the following:

  • All numeric, interval, and ordinal type columns from the original dataset.
  • Binary categorical features (all numerically-encoded).
  • Engineered features from other multi-level categorical features and mixed features.

Make sure that for any new columns that you have engineered, that you've excluded the original columns from the final dataset. Otherwise, their values will interfere with the analysis later on the project. For example, you should not keep "PRAEGENDE_JUGENDJAHRE", since its values won't be useful for the algorithm: only the values derived from it in the engineered features you created should be retained. As a reminder, your data should only be from the subset with few or no missing values.

In [20]:
# If there are other re-engineering tasks you need to perform, make sure you
# take care of them here. (Dealing with missing data will come in step 2.1.)

azdias_clean_df.drop(['PRAEGENDE_JUGENDJAHRE','CAMEO_INTL_2015'], axis=1, inplace=True)
In [21]:
# Do whatever you need to in order to ensure that the dataframe only contains
# the columns that should be passed to the algorithm functions.

azdias_clean_df.head(2)
Out[21]:
ALTERSKATEGORIE_GROB ANREDE_KZ FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER GREEN_AVANTGARDE HEALTH_TYP ... PLZ8_BAUMAX PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB PRAEGENDE_JUGENDJAHRE_DECADE PRAEGENDE_JUGENDJAHRE_REGION CAMEO_INTL_2015_WEALTH CAMEO_INTL_2015_LIFE_STAGE
0 2.0 1 3 4 3 5 5 3 0 NaN ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
1 1.0 2 1 5 2 5 4 5 0 3.0 ... 1.0 5.0 4.0 3.0 5.0 4.0 14.0 1.0 5.0 1.0

2 rows × 68 columns

Step 1.3: Create a Cleaning Function

Even though you've finished cleaning up the general population demographics data, it's important to look ahead to the future and realize that you'll need to perform the same cleaning steps on the customer demographics data. In this substep, complete the function below to execute the main feature selection, encoding, and re-engineering steps you performed above. Then, when it comes to looking at the customer data in Step 3, you can just run this function on that DataFrame to get the trimmed dataset in a single step.

In [22]:
def clean_data(df):
    """
    Perform feature trimming, re-encoding, and engineering for demographics
    data
    
    INPUT: Demographics DataFrame
    OUTPUT: Trimmed and cleaned demographics DataFrame
    """
    
    
    # Put in code here to execute all main cleaning steps:
    
    ## convert missing value codes into NaNs, ...
    
    # Copy Data
    feat_info_clean_df = feat_info.copy(deep=True)
    azdias_clean_df = df.copy(deep=True)
    
    # Remove symbols
    feat_info_clean_df.missing_or_unknown = feat_info_clean_df.missing_or_unknown.apply(list_split)
    feat_info_clean_df.set_index(['attribute'], inplace=True)
    
    # Replace
    for attr in feat_info_clean_df.index:  ## For each column attribute                                 
        for x in feat_info_clean_df.loc[attr]['missing_or_unknown']: ## Extract number values in that column
            try:
                azdias_clean_df[attr].replace(int(x), np.nan, inplace=True) ## Replace those number values by NaN
            except ValueError:    
                azdias_clean_df[attr].replace(x, np.nan, inplace=True) ## Exception if value error (not int), then replace whole x with nan


    
    ## remove selected columns and rows, ...
    
    # Remove columns hosting 30%+ Nulls
    cleaned_nulls_count = azdias_clean_df.isnull().sum()
    cleaned_nulls_count_df = pd.DataFrame(cleaned_nulls_count).reset_index().rename(columns={'index':'feature',0:'count'})
    cleaned_nulls_count_df['percentage'] = cleaned_nulls_count_df['count']/azdias_clean_df.shape[0]
    cleaned_nulls_count_df.sort_values(by = 'percentage', ascending = False, inplace=True)
    
    outlier_columns = cleaned_nulls_count_df[cleaned_nulls_count_df.percentage > 0.3]['feature']
    azdias_clean_df.drop(outlier_columns, axis=1, inplace=True)
    
    # Remove rows more than 10 missing values
    cleaned_nullrows_count = azdias_clean_df.isnull().sum(axis=1)
    cleaned_nullrows_count_df = pd.DataFrame(cleaned_nullrows_count).reset_index().rename(columns={'index':'row',0:'count'})
    cleaned_nullrows_count_df['percentage'] = cleaned_nullrows_count_df['count']/azdias_clean_df.shape[1]
    
    outlier_rows = cleaned_nullrows_count_df[cleaned_nullrows_count_df['count'] > 10].index
    azdias_clean_df.drop(outlier_rows, axis=0, inplace=True)


    ## select, re-encode, and engineer column values.
    
    # Re-Encode categorical non-numerical column
    azdias_clean_df.replace({'OST_WEST_KZ':{'W': 0, 'O': 1}}, inplace=True)

    # Drop multivariate columns (variates > 3)
    cat_columns = feat_info.query("type == 'categorical'")['attribute']
    mixed_columns = feat_info.query("type == 'mixed'")['attribute']
    
    uniq_df = pd.DataFrame(azdias_clean_df[azdias_clean_df.columns.intersection(cat_columns)].nunique(), columns=['nunique'])
    type_df = pd.DataFrame(azdias_clean_df[azdias_clean_df.columns.intersection(cat_columns)].dtypes, columns=['dtype'])
    cat_columns_df = pd.concat([uniq_df,type_df], axis=1).sort_values(by='nunique')
    
    azdias_clean_df.drop(cat_columns_df[cat_columns_df['nunique']>=3].index, axis=1, inplace=True)
    
    # Mixed columns
    azdias_clean_df['PRAEGENDE_JUGENDJAHRE_DECADE'] = azdias_clean_df['PRAEGENDE_JUGENDJAHRE'].apply(get_decade)
    azdias_clean_df['PRAEGENDE_JUGENDJAHRE_REGION'] = azdias_clean_df['PRAEGENDE_JUGENDJAHRE'].apply(get_region)
    azdias_clean_df['CAMEO_INTL_2015_WEALTH'] = azdias_clean_df['CAMEO_INTL_2015'].apply(get_wealth)
    azdias_clean_df['CAMEO_INTL_2015_LIFE_STAGE'] = azdias_clean_df['CAMEO_INTL_2015'].apply(life_stage)
    
    azdias_clean_df.drop(['PRAEGENDE_JUGENDJAHRE','CAMEO_INTL_2015'], axis=1, inplace=True)

    print("Original shape:", df.shape)
    print("After cleansing shape:", azdias_clean_df.shape)
    return azdias_clean_df
    ## Return the cleaned dataframe.
    
    
In [23]:
azdias_clean_df = clean_data(azdias)
Original shape: (891221, 85)
After cleansing shape: (780153, 68)

Step 2: Feature Transformation

Step 2.1: Apply Feature Scaling

Before we apply dimensionality reduction techniques to the data, we need to perform feature scaling so that the principal component vectors are not influenced by the natural differences in scale for features. Starting from this part of the project, you'll want to keep an eye on the API reference page for sklearn to help you navigate to all of the classes and functions that you'll need. In this substep, you'll need to check the following:

  • sklearn requires that data not have missing values in order for its estimators to work properly. So, before applying the scaler to your data, make sure that you've cleaned the DataFrame of the remaining missing values. This can be as simple as just removing all data points with missing data, or applying an Imputer to replace all missing values. You might also try a more complicated procedure where you temporarily remove missing values in order to compute the scaling parameters before re-introducing those missing values and applying imputation. Think about how much missing data you have and what possible effects each approach might have on your analysis, and justify your decision in the discussion section below.
  • For the actual scaling function, a StandardScaler instance is suggested, scaling each feature to mean 0 and standard deviation 1.
  • For these classes, you can make use of the .fit_transform() method to both fit a procedure to the data as well as apply the transformation to the data at the same time. Don't forget to keep the fit sklearn objects handy, since you'll be applying them to the customer demographics data towards the end of the project.
In [24]:
# If you've not yet cleaned the dataset of all NaN values, then investigate and
# do that now.
azdias_clean_df.isnull().sum().sort_values(ascending=False) / len(azdias_clean_df) * 100
Out[24]:
W_KEIT_KIND_HH         7.214226
REGIOTYP               7.021443
KKK                    7.021443
LP_LEBENSPHASE_FEIN    5.969855
LP_LEBENSPHASE_GROB    5.626332
                         ...   
SEMIO_KRIT             0.000000
SEMIO_RAT              0.000000
SEMIO_KULT             0.000000
SEMIO_ERL              0.000000
WOHNDAUER_2008         0.000000
Length: 68, dtype: float64
Scaling - The complex way
In [25]:
azdias_clean_df = azdias_clean_df.sub(azdias_clean_df.mean())/azdias_clean_df.std()
Missing data imputation
In [26]:
## Instantiate an imputer ##
mean_imputer = SimpleImputer(missing_values=np.nan, strategy='mean', copy=False)
## Fit an imputer ##
mean_imputer.fit(azdias_clean_df)
## Transform using imputer ##
mean_imputer.transform(azdias_clean_df)
## Validate all nulls are dropped ##
print("[validation] Unique nulls sum: ",np.unique(azdias_clean_df.isnull().sum(axis=1)))
print("Shape after cleaning: ", azdias_clean_df.shape)
[validation] Unique nulls sum:  [0]
Shape after cleaning:  (780153, 68)

Discussion 2.1: Apply Feature Scaling

sklearn standard scalar takes into account missing nan values, meaning if we have a column of 4 values and one nan, it will divide on 5.

So I'm going to play with df.sub, df.mean and df.std to calculate the mean of columns and standard deivation excluding the nans which divides on row number excluding nans. I've simulated this way and the numbers matches the standard scaler of sklearn's. The validation can be done when having a mean of 0 and a std of 1 for each column, this has to be done using np.nanmean()

Step 2.2: Perform Dimensionality Reduction

On your scaled data, you are now ready to apply dimensionality reduction techniques.

  • Use sklearn's PCA class to apply principal component analysis on the data, thus finding the vectors of maximal variance in the data. To start, you should not set any parameters (so all components are computed) or set a number of components that is at least half the number of features (so there's enough features to see the general trend in variability).
  • Check out the ratio of variance explained by each principal component as well as the cumulative variance explained. Try plotting the cumulative or sequential values using matplotlib's plot() function. Based on what you find, select a value for the number of transformed features you'll retain for the clustering part of the project.
  • Once you've made a choice for the number of components to keep, make sure you re-fit a PCA instance to perform the decided-on transformation.
In [27]:
# Apply PCA to the data.

def do_pca(n_components, data):
    '''
    Transforms data using PCA to create n_components, and provides back the results of the
    transformation.
    
    INPUT: n_components - int - the number of principal components to create
           data - the data you would like to transform
           
    OUTPUT: pca - the pca object created after fitting the data
            X_pca - the transformed X matrix with new number of components
    '''
    pca = PCA(n_components)
    X_pca = pca.fit_transform(data)
    return pca, X_pca

pca, X_pca = do_pca(68,azdias_clean_df)
In [28]:
# Investigate the variance accounted for by each principal component.

def scree_plot(pca):
    '''
    Creates a scree plot associated with the principal components 
    
    INPUT: pca - the result of instantian of PCA in scikit learn
            
    OUTPUT:
            None
    '''
    num_components=len(pca.explained_variance_ratio_)
    ind = np.arange(num_components)
    vals = pca.explained_variance_ratio_
 
    plt.figure(figsize=(15, 10))
    ax = plt.subplot(111)
    cumvals = np.cumsum(vals)
    ax.bar(ind, vals)
    ax.plot(ind, cumvals)
    for i in range(num_components):
        ax.annotate(r"%s%%" % ((str(vals[i]*100)[:4])), (ind[i]+0.2, vals[i]), 
                    va="bottom", 
                    ha="center", 
                    fontsize=10, 
                    rotation = 90)

    ax.xaxis.set_tick_params(width=0)
    ax.yaxis.set_tick_params(width=2, length=11)
 
    ax.set_xlabel("Principal Component")
    ax.set_ylabel("Variance Explained (%)")
    plt.title('Explained Variance Per Principal Component')

scree_plot(pca)
In [29]:
# Re-apply PCA to the data while selecting for number of components to retain.
pca, X_pca = do_pca(25,azdias_clean_df)
scree_plot(pca)

Discussion 2.2: Perform Dimensionality Reduction

We can see that we're reaching 80.5% variance by the 23rd component.

Step 2.3: Interpret Principal Components

Now that we have our transformed principal components, it's a nice idea to check out the weight of each variable on the first few components to see if they can be interpreted in some fashion.

As a reminder, each principal component is a unit vector that points in the direction of highest variance (after accounting for the variance captured by earlier principal components). The further a weight is from zero, the more the principal component is in the direction of the corresponding feature. If two features have large weights of the same sign (both positive or both negative), then increases in one tend expect to be associated with increases in the other. To contrast, features with different signs can be expected to show a negative correlation: increases in one variable should result in a decrease in the other.

  • To investigate the features, you should map each weight to their corresponding feature name, then sort the features according to weight. The most interesting features for each principal component, then, will be those at the beginning and end of the sorted list. Use the data dictionary document to help you understand these most prominent features, their relationships, and what a positive or negative value on the principal component might indicate.
  • You should investigate and interpret feature associations from the first three principal components in this substep. To help facilitate this, you should write a function that you can call at any time to print the sorted list of feature weights, for the i-th principal component. This might come in handy in the next step of the project, when you interpret the tendencies of the discovered clusters.
In [30]:
def pca_results(full_dataset, pca, n_comp, visual=True):
    '''
	Create a DataFrame of the PCA results
	Includes dimension feature weights and explained variance
	Visualizes the PCA results
	'''

    # Dimension indexing
    dimensions = dimensions = ['Dimension {}'.format(i) for i in range(1,n_comp+1)]

    # PCA components
    components = pd.DataFrame(np.round(pca.components_[1:n_comp+1], 4), columns = full_dataset.keys())
    components.index = dimensions

    # PCA explained variance
    ratios = pca.explained_variance_ratio_[0:n_comp].reshape(n_comp, 1)
    variance_ratios = pd.DataFrame(np.round(ratios, 4), columns = ['Explained Variance'])
    variance_ratios.index = dimensions
    if visual == True:
        # Create a bar plot visualization
        fig, ax = plt.subplots(figsize = (14,8))

        # Plot the feature weights as a function of the components
        components.plot(ax = ax, kind = 'bar');
        ax.set_ylabel("Feature Weights")
        ax.set_xticklabels(dimensions, rotation=0)
        ax.get_legend().remove()

        # Display the explained variance ratios
        for i, ev in enumerate(pca.explained_variance_ratio_[0:n_comp]):
            ax.text(i-0.40, ax.get_ylim()[1] + 0.05, "Explained Variance\n          %.4f"%(ev))
    else:
        # Return a concatenated DataFrame
        return pd.concat([variance_ratios, components], axis = 1)

pca_results(azdias_clean_df,pca,3, visual=False)
Out[30]:
Explained Variance ALTERSKATEGORIE_GROB ANREDE_KZ FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER GREEN_AVANTGARDE ... PLZ8_BAUMAX PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB PRAEGENDE_JUGENDJAHRE_DECADE PRAEGENDE_JUGENDJAHRE_REGION CAMEO_INTL_2015_WEALTH CAMEO_INTL_2015_LIFE_STAGE
Dimension 1 0.1725 0.2717 0.0898 0.0942 -0.2509 0.2434 -0.2119 -0.2346 0.0901 -0.0002 ... 0.0584 0.0086 -0.0513 0.0491 0.0681 0.0481 -0.2420 -0.0212 0.0472 0.0104
Dimension 2 0.1280 0.0845 -0.3703 0.1658 -0.1120 0.1049 -0.1912 -0.1049 -0.0531 0.0449 ... 0.0422 0.0014 -0.0352 0.0296 0.0391 0.0263 -0.1024 0.0078 0.0215 -0.0093
Dimension 3 0.0898 -0.0332 0.0265 0.0940 -0.0140 -0.0097 -0.1069 0.0496 -0.1351 0.3136 ... 0.0774 0.0874 -0.0111 0.0854 0.2526 0.1113 0.0117 0.0901 -0.1084 0.0418

3 rows × 69 columns

In [31]:
# Map weights for the first principal component to corresponding feature names
# and then print the linked values, sorted by weight.
# HINT: Try defining a function here or in a new cell that you can reuse in the
# other cells.
pca_01_df = pd.DataFrame(np.round(pca.components_[0:1], 4), columns = azdias_clean_df.keys()).T.rename(columns={0:'Weight'})
pca_01_df['Weight_abs'] = np.abs(pca_01_df['Weight'])
pca_01_df.sort_values(by = 'Weight_abs', ascending=False)[:10]
Out[31]:
Weight Weight_abs
MOBI_REGIO -0.2333 0.2333
PLZ8_ANTG3 0.2268 0.2268
PLZ8_ANTG1 -0.2255 0.2255
PLZ8_ANTG4 0.2207 0.2207
PLZ8_BAUMAX 0.2160 0.2160
KBA05_ANTG1 -0.2159 0.2159
KBA05_GBZ -0.2092 0.2092
ORTSGR_KLS9 0.2021 0.2021
FINANZ_MINIMALIST -0.2012 0.2012
CAMEO_INTL_2015_WEALTH 0.2011 0.2011
In [32]:
# Map weights for the second principal component to corresponding feature names
# and then print the linked values, sorted by weight.
pca_02_df = pd.DataFrame(np.round(pca.components_[1:2], 4), columns = azdias_clean_df.keys()).T.rename(columns={0:'Weight'})
pca_02_df['Weight_abs'] = np.abs(pca_02_df['Weight'])
pca_02_df.sort_values(by = 'Weight_abs', ascending=False)[:10]
Out[32]:
Weight Weight_abs
ALTERSKATEGORIE_GROB 0.2717 0.2717
SEMIO_REL -0.2679 0.2679
FINANZ_SPARER -0.2509 0.2509
FINANZ_VORSORGER 0.2434 0.2434
PRAEGENDE_JUGENDJAHRE_DECADE -0.2420 0.2420
SEMIO_PFLICHT -0.2405 0.2405
SEMIO_TRADV -0.2396 0.2396
SEMIO_ERL 0.2393 0.2393
FINANZ_UNAUFFAELLIGER -0.2346 0.2346
SEMIO_KULT -0.2280 0.2280
In [33]:
# Map weights for the third principal component to corresponding feature names
# and then print the linked values, sorted by weight.

pca_03_df = pd.DataFrame(np.round(pca.components_[2:3], 4), columns = azdias_clean_df.keys()).T.rename(columns={0:'Weight'})
pca_03_df['Weight_abs'] = np.abs(pca_03_df['Weight'])
pca_03_df.sort_values(by = 'Weight_abs', ascending=False)[:10]
Out[33]:
Weight Weight_abs
ANREDE_KZ -0.3703 0.3703
SEMIO_VERT 0.3482 0.3482
SEMIO_KAEM -0.3385 0.3385
SEMIO_DOM -0.3141 0.3141
SEMIO_KRIT -0.2736 0.2736
SEMIO_SOZ 0.2616 0.2616
SEMIO_FAM 0.2472 0.2472
SEMIO_KULT 0.2320 0.2320
SEMIO_RAT -0.2216 0.2216
FINANZ_ANLEGER -0.1912 0.1912
In [34]:
pca_results(azdias_clean_df,pca,3, visual=True)

Discussion 2.3: Interpret Principal Components

PCA-1

- MOBI_REGIO:                   Movement patterns   
- PLZ8_ANTG3:                   Number of 6-10 family houses in the PLZ8 region
- PLZ8_ANTG1:                   Number of 1-2 family houses in the PLZ8 region
- PLZ8_ANTG4:                   Number of 10+ family houses in the PLZ8 region
- PLZ8_BAUMAX:                  Most common building type within the PLZ8 region
- CAMEO_INTL_2015_WEALTH:       Wealth of family        

In the positive co-relation we can see that:

  • We can see both PLZ8_ANTG3 and PLZ8_ANTG4 increase togther having +ve corelation, since large families (6-10 and 10+) share the same size of house hold.

  • PLZ8_ANTG3 and CAMEO_INTL_2015_WEALTH we can see a +ve co-relation which seems to indicate large families are poor

In the negative cor-relation we can see that:

  • Finally we can see from MOBI_REGIO,PLZ8_ANTG1 and FINANZ_MINIMALIST that smaller families in the PLZ8 region tend to be less interested in finicial matters and they move less compared to the larger densities.these are related to movement patterns.

PCA-2

- ALTERSKATEGORIE_GROB:         Estimated age based on given name analysis  
- SEMIO_REL:                    Personality typology, for each dimension
- FINANZ_SPARER:                Financial typology
- FINANZ_VORSORGER:             Financial typology
- PRAEGENDE_JUGENDJAHRE_DECADE: Generation by the decade
- SEMIO_PFLICHT:                Personality typology    


In the positive co-relation we can see that: ALTERSKATEGORIE_GROB, FINANZ_VORSORGER and SEMIO_ERL It seems that this component is related more to personality, age and financial readiness.

In the negative weights: SEMIO_REL, FINANZ_SPARER, PRAEGENDE_JUGENDJAHRE_DECADE we can that older religous people tend to save money more.


PCA-3

- ANREDE_KZ:    Gender              
- SEMIO_VERT:   Personality typology                    
- SEMIO_KAEM:   Personality typology           
- SEMIO_DOM:    Personality typology            
- SEMIO_KRIT:   Personality typology                
- SEMIO_FAM:    Personality typology            

This component is purely psychological.

For the positive corelations: VERT, SOZ and FAM it indicates dreamful, socially-minded and family minded a person is.

For the negative corelations: ANREDE_KZ, SEMIO_KAEM, SEMIO_DOM, KRIT, SEMIO_RAT they type of gender and personalities that have combative attitude, dominant-minded, critical and rational .. they seem to be mostly men.


Step 3: Clustering

Step 3.1: Apply Clustering to General Population

You've assessed and cleaned the demographics data, then scaled and transformed them. Now, it's time to see how the data clusters in the principal components space. In this substep, you will apply k-means clustering to the dataset and use the average within-cluster distances from each point to their assigned cluster's centroid to decide on a number of clusters to keep.

  • Use sklearn's KMeans class to perform k-means clustering on the PCA-transformed data.
  • Then, compute the average difference from each point to its assigned cluster's center. Hint: The KMeans object's .score() method might be useful here, but note that in sklearn, scores tend to be defined so that larger is better. Try applying it to a small, toy dataset, or use an internet search to help your understanding.
  • Perform the above two steps for a number of different cluster counts. You can then see how the average distance decreases with an increasing number of clusters. However, each additional cluster provides a smaller net benefit. Use this fact to select a final number of clusters in which to group the data. Warning: because of the large size of the dataset, it can take a long time for the algorithm to resolve. The more clusters to fit, the longer the algorithm will take. You should test for cluster counts through at least 10 clusters to get the full picture, but you shouldn't need to test for a number of clusters above about 30.
  • Once you've selected a final number of clusters to use, re-fit a KMeans instance to perform the clustering operation. Make sure that you also obtain the cluster assignments for the general demographics data, since you'll be using them in the final Step 3.3.
Dataframe sampling
In [35]:
X_pca_sample = pd.DataFrame(X_pca).sample(frac=0.2, random_state=1)

print("Original rows:",len(X_pca),"\nSample rows:", len(X_pca_sample))
Original rows: 780153 
Sample rows: 156031
In [36]:
# Over a number of different cluster counts...
start_time = time.time()

def do_kmeans_scores(data, n_cluster, njobs):
    
    def kmeans_fit(data,n_cluster, njobs):
        kmeans = KMeans(n_clusters = n_cluster, n_jobs=njobs)
        model = kmeans.fit(data)
        return np.abs(model.score(data))
    scores = []
    for k in list(range(1,n_cluster+1)):
        st_time = time.time()
        score = kmeans_fit(data,k,njobs)
        scores.append(score)
        end_time = time.time()
        print(k,"- Score:",np.round(score),"| Run time: %s mins" % np.round(((end_time - st_time)/60),3))    
    return scores, print("=== Total Run time: %s mins ===" % np.round(((time.time() - start_time)/60),2))

# run k-means clustering on the data and...
# compute the average within-cluster distances.

scores = do_kmeans_scores(X_pca_sample,30, njobs = -1)
1 - Score: 8667942.0 | Run time: 0.043 mins
2 - Score: 7313343.0 | Run time: 0.041 mins
3 - Score: 6682301.0 | Run time: 0.05 mins
4 - Score: 6253267.0 | Run time: 0.068 mins
5 - Score: 5963860.0 | Run time: 0.072 mins
6 - Score: 5724157.0 | Run time: 0.082 mins
7 - Score: 5501603.0 | Run time: 0.089 mins
8 - Score: 5334174.0 | Run time: 0.131 mins
9 - Score: 5235503.0 | Run time: 0.131 mins
10 - Score: 5143983.0 | Run time: 0.171 mins
11 - Score: 5002855.0 | Run time: 0.154 mins
12 - Score: 4918708.0 | Run time: 0.203 mins
13 - Score: 4851181.0 | Run time: 0.268 mins
14 - Score: 4790306.0 | Run time: 0.29 mins
15 - Score: 4781012.0 | Run time: 0.224 mins
16 - Score: 4667453.0 | Run time: 0.268 mins
17 - Score: 4512738.0 | Run time: 0.317 mins
18 - Score: 4497298.0 | Run time: 0.324 mins
19 - Score: 4410203.0 | Run time: 0.395 mins
20 - Score: 4492678.0 | Run time: 0.392 mins
21 - Score: 4325363.0 | Run time: 0.45 mins
22 - Score: 4329309.0 | Run time: 0.421 mins
23 - Score: 4247812.0 | Run time: 0.509 mins
24 - Score: 4206380.0 | Run time: 0.442 mins
25 - Score: 4174939.0 | Run time: 0.52 mins
26 - Score: 4149925.0 | Run time: 0.531 mins
27 - Score: 4106052.0 | Run time: 0.654 mins
28 - Score: 4089272.0 | Run time: 0.718 mins
29 - Score: 4074714.0 | Run time: 0.594 mins
30 - Score: 4032430.0 | Run time: 0.73 mins
=== Total Run time: 9.28 mins ===
In [37]:
# Investigate the change in within-cluster distance across number of clusters.
# HINT: Use matplotlib's plot function to visualize this relationship.

plt.plot(list(range(1,30+1)), scores[0], linestyle='--', marker='o', color='b');
plt.xlabel('K');
plt.ylabel('SSE');
plt.title('SSE vs. K');
In [38]:
# Re-fit the k-means model with the selected number of clusters and obtain
# cluster predictions for the general population demographics data.
kmeans =  KMeans(n_clusters = 25, n_jobs=-1)
model = kmeans.fit(X_pca)
azdias_pred = model.predict(X_pca)

Discussion 3.1: Apply Clustering to General Population

There isn't a specific elbow, but we can see the curve and the sum of squared distances error (sse) seems to getting lower. I will choose 25 clusters, since after that the k klusters seems to converge.

Step 3.2: Apply All Steps to the Customer Data

Now that you have clusters and cluster centers for the general population, it's time to see how the customer data maps on to those clusters. Take care to not confuse this for re-fitting all of the models to the customer data. Instead, you're going to use the fits from the general population to clean, transform, and cluster the customer data. In the last step of the project, you will interpret how the general population fits apply to the customer data.

  • Don't forget when loading in the customers data, that it is semicolon (;) delimited.
  • Apply the same feature wrangling, selection, and engineering steps to the customer demographics using the clean_data() function you created earlier. (You can assume that the customer demographics data has similar meaning behind missing data patterns as the general demographics data.)
  • Use the sklearn objects from the general demographics data, and apply their transformations to the customers data. That is, you should not be using a .fit() or .fit_transform() method to re-fit the old objects, nor should you be creating new sklearn objects! Carry the data through the feature scaling, PCA, and clustering steps, obtaining cluster assignments for all of the data in the customer demographics data.
In [39]:
# Load in the customer demographics data.
customers_df = pd.read_csv('Udacity_CUSTOMERS_Subset.csv', sep=';')
customers_df.head(2)
Out[39]:
AGER_TYP ALTERSKATEGORIE_GROB ANREDE_KZ CJT_GESAMTTYP FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER ... PLZ8_ANTG1 PLZ8_ANTG2 PLZ8_ANTG3 PLZ8_ANTG4 PLZ8_BAUMAX PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB
0 2 4 1 5.0 5 1 5 1 2 2 ... 3.0 3.0 1.0 0.0 1.0 5.0 5.0 1.0 2.0 1.0
1 -1 4 1 NaN 5 1 5 1 3 2 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

2 rows × 85 columns

In [41]:
# Apply preprocessing, feature transformation, and clustering from the general
# demographics onto the customer data, obtaining cluster predictions for the
# customer demographics data.

customers_clean_df = clean_data(customers_df)
Original shape: (191652, 85)
After cleansing shape: (139259, 66)
Scaling variable (standard scalar)
In [42]:
customers_clean_df = customers_clean_df.sub(customers_clean_df.mean())/customers_clean_df.std()
Missing data imputation
In [43]:
## Fit an imputer ##
mean_imputer.fit(customers_clean_df)
## Transform using imputer ##
mean_imputer.transform(customers_clean_df)
## Validate all nulls are dropped ##
print("[validation] Unique nulls sum: ",np.unique(customers_clean_df.isnull().sum(axis=1)))
[validation] Unique nulls sum:  [0]
PCA
In [44]:
customers_pca, customers_X_pca = do_pca(25,customers_clean_df)
Prediction
In [45]:
customers_pred = model.predict(customers_X_pca)

Step 3.3: Compare Customer Data to Demographics Data

At this point, you have clustered data based on demographics of the general population of Germany, and seen how the customer data for a mail-order sales company maps onto those demographic clusters. In this final substep, you will compare the two cluster distributions to see where the strongest customer base for the company is.

Consider the proportion of persons in each cluster for the general population, and the proportions for the customers. If we think the company's customer base to be universal, then the cluster assignment proportions should be fairly similar between the two. If there are only particular segments of the population that are interested in the company's products, then we should see a mismatch from one to the other. If there is a higher proportion of persons in a cluster for the customer data compared to the general population (e.g. 5% of persons are assigned to a cluster for the general population, but 15% of the customer data is closest to that cluster's centroid) then that suggests the people in that cluster to be a target audience for the company. On the other hand, the proportion of the data in a cluster being larger in the general population than the customer data (e.g. only 2% of customers closest to a population centroid that captures 6% of the data) suggests that group of persons to be outside of the target demographics.

Take a look at the following points in this step:

  • Compute the proportion of data points in each cluster for the general population and the customer data. Visualizations will be useful here: both for the individual dataset proportions, but also to visualize the ratios in cluster representation between groups. Seaborn's countplot() or barplot() function could be handy.
    • Recall the analysis you performed in step 1.1.3 of the project, where you separated out certain data points from the dataset if they had more than a specified threshold of missing values. If you found that this group was qualitatively different from the main bulk of the data, you should treat this as an additional data cluster in this analysis. Make sure that you account for the number of data points in this subset, for both the general population and customer datasets, when making your computations!
  • Which cluster or clusters are overrepresented in the customer dataset compared to the general population? Select at least one such cluster and infer what kind of people might be represented by that cluster. Use the principal component interpretations from step 2.3 or look at additional components to help you make this inference. Alternatively, you can use the .inverse_transform() method of the PCA and StandardScaler objects to transform centroids back to the original data space and interpret the retrieved values directly.
  • Perform a similar investigation for the underrepresented clusters. Which cluster or clusters are underrepresented in the customer dataset compared to the general population, and what kinds of people are typified by these clusters?
In [46]:
# Compare the proportion of data in each cluster for the customer data to the
# proportion of data in each cluster for the general population.

figure, axs = plt.subplots(nrows=1, ncols=2, figsize = (15,5))
figure.subplots_adjust(hspace = 1, wspace=.3)

sns.countplot(customers_pred, ax=axs[0])
axs[0].set_title('Customer Clusters')
sns.countplot(azdias_pred, ax=axs[1])
axs[1].set_title('General Clusters')
Out[46]:
Text(0.5, 1.0, 'General Clusters')
In [47]:
#general_pred_df = pd.DataFrame(azdias_pred, columns=['count'])['count'].value_counts().sort_index()

general_pred_df = pd.DataFrame(pd.DataFrame(azdias_pred, columns=['count'])['count'].value_counts().sort_index())
general_pred_df['prop'] = general_pred_df['count'] / len(azdias_pred)

customers_pred_df = pd.DataFrame(pd.DataFrame(customers_pred, columns=['count'])['count'].value_counts().sort_index())
customers_pred_df['prop'] = customers_pred_df['count'] / len(customers_pred)


fig = go.Figure()

fig.update_layout(
    title = {'text':'General vs. Customers proportions', 'x': 0.5},
    xaxis_title = "clusters",
    yaxis_title = "proportions",
    xaxis = dict(
        tickmode = 'linear',
        tick0 = 0,
        dtick = 1
    )
)

             
fig.add_trace(go.Bar(x=general_pred_df.index,
                y=general_pred_df['prop'],
                name='General',
                marker_color='#ABDDDE'
                ))

fig.add_trace(go.Bar(x=customers_pred_df.index,
                y=customers_pred_df['prop'],
                name='Customers',
                marker_color='rgb(244, 181, 189)'
                ))
In [48]:
# Check difference in cluster proportion for general vs customer populations
prop_diff = (customers_pred_df.prop-general_pred_df.prop).sort_values(ascending=False)
print("over-represented:")
display(prop_diff[0:3])
print("under-represented:")
display(prop_diff[-3:])
over-represented:
24    0.023459
17    0.022391
22    0.021838
Name: prop, dtype: float64
under-represented:
12   -0.012883
11   -0.012959
23   -0.032358
Name: prop, dtype: float64
In [67]:
prop_diff.sort_index(inplace=True)
fig = go.Figure()
fig = go.Figure(data=go.Scatter(x=prop_diff.index, 
                                y=prop_diff.values,
                                mode='lines+markers',
                                line_color='#ABDDDE',
                                marker_color='rgb(244, 181, 189)'))

fig.update_layout(title = {'text':'General vs. Customers proportions', 'x': 0.5},
                  xaxis = dict(
                      title = "clusters",
                      tickmode = 'linear',
                      tick0 = 0,
                      dtick = 1),
                  yaxis_title = "proportions"
                 )

fig.show()
In [50]:
# What kinds of people are part of a cluster that is overrepresented in the
# customer data compared to the general population?

pca_inv_df_cent12 = pd.DataFrame(customers_pca.inverse_transform(customers_X_pca[customers_pred == 12]))
target_cent_12 = pca_inv_df_cent12.mul(pca_inv_df_cent12.std())+pca_inv_df_cent12.mean()
target_cent_12.columns = customers_clean_df.columns
target_cent_12.describe()
Out[50]:
ALTERSKATEGORIE_GROB ANREDE_KZ FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER GREEN_AVANTGARDE HEALTH_TYP ... PLZ8_BAUMAX PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB PRAEGENDE_JUGENDJAHRE_DECADE PRAEGENDE_JUGENDJAHRE_REGION CAMEO_INTL_2015_WEALTH CAMEO_INTL_2015_LIFE_STAGE
count 2734.000000 2734.000000 2734.000000 2734.000000 2734.000000 2734.000000 2734.000000 2734.000000 2734.000000 2734.000000 ... 2734.000000 2734.000000 2734.000000 2734.000000 2734.000000 2734.000000 2734.000000 2734.000000 2734.000000 2734.000000
mean 0.319996 -0.859216 -1.244761 -0.437247 0.616191 -0.971300 -0.835631 1.591721 -0.963588 -0.348216 ... 2.483279 0.575268 -1.734602 0.881507 1.479002 1.062349 -0.577965 -0.574800 1.749681 -0.536067
std 0.325380 0.048090 0.156774 0.034532 0.068945 0.073743 0.195617 0.146392 0.360891 0.627353 ... 0.644726 0.588717 0.793988 0.365501 0.288480 0.403553 0.038781 0.399133 0.412571 1.428725
min -0.983441 -1.047081 -1.625935 -0.517970 0.180882 -1.174527 -1.410670 0.928028 -1.785966 -1.599090 ... 0.657169 -1.182510 -3.860697 -0.653256 0.277487 -0.657390 -0.681028 -1.145727 0.552652 -3.107264
25% 0.059885 -0.890927 -1.345710 -0.460129 0.588924 -1.022453 -0.908332 1.512478 -1.207822 -0.810148 ... 1.920061 0.099394 -2.324213 0.731773 1.291671 0.811851 -0.603792 -0.750093 1.428376 -2.132111
50% 0.345632 -0.859353 -1.272815 -0.441796 0.631818 -0.978686 -0.816079 1.599812 -1.057094 -0.432216 ... 2.569847 0.562601 -1.754504 0.915460 1.549077 1.133063 -0.581955 -0.652163 1.766325 -0.134558
75% 0.551030 -0.829254 -1.185792 -0.419994 0.663623 -0.929610 -0.711579 1.683500 -0.818371 0.117782 ... 3.034933 1.017742 -1.265577 1.140773 1.706362 1.356636 -0.558388 -0.550925 2.076816 0.764706
max 1.076849 -0.703903 -0.574874 -0.200393 0.781080 -0.613777 -0.127786 2.037987 0.350895 1.323321 ... 3.826954 2.449344 0.624720 1.903987 2.095769 2.019654 -0.330322 2.201345 3.249774 2.019858

8 rows × 66 columns

In [51]:
# What kinds of people are part of a cluster that is underrepresented in the
# customer data compared to the general population?
pca_inv_df_cent21 = pd.DataFrame(pca.inverse_transform(X_pca[azdias_pred == 21]))
outside_cent_21 = pca_inv_df_cent21.mul(pca_inv_df_cent21.std())+pca_inv_df_cent21.mean()
outside_cent_21.columns = azdias_clean_df.columns
outside_cent_21.describe()
Out[51]:
ALTERSKATEGORIE_GROB ANREDE_KZ FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER GREEN_AVANTGARDE HEALTH_TYP ... PLZ8_BAUMAX PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB PRAEGENDE_JUGENDJAHRE_DECADE PRAEGENDE_JUGENDJAHRE_REGION CAMEO_INTL_2015_WEALTH CAMEO_INTL_2015_LIFE_STAGE
count 6507.000000 6507.000000 6507.000000 6507.000000 6507.000000 6507.000000 6507.000000 6507.000000 6507.000000 6507.000000 ... 6507.000000 6507.000000 6507.000000 6507.000000 6507.000000 6507.000000 6507.000000 6507.000000 6507.000000 6507.000000
mean -0.047442 -0.047941 0.098142 0.019382 0.008016 0.018763 0.040436 -0.143271 -0.031000 -0.117558 ... -0.039277 -0.001001 0.047024 -0.066303 -0.062103 0.007499 0.028103 0.060229 -0.200612 0.081401
std 0.905327 0.929590 0.872806 0.908634 0.852858 0.794619 0.831219 0.813219 0.713451 0.788263 ... 0.752980 0.907415 0.893331 0.886022 0.853192 0.847994 0.844935 0.870542 0.702291 0.887709
min -2.052522 -1.740943 -2.093970 -1.533680 -1.972397 -1.866003 -1.699027 -2.752081 -1.547121 -2.309587 ... -1.480627 -2.809941 -2.818724 -2.248631 -1.984164 -2.236022 -1.612101 -1.275243 -1.998728 -1.723900
25% -0.840531 -0.971386 -0.537862 -0.855165 -0.811580 -0.641853 -0.673477 -0.742763 -0.548908 -0.683510 ... -0.624403 -0.581619 -0.504647 -0.681393 -0.743266 -0.567352 -0.670710 -0.512077 -0.786662 -0.890594
50% 0.126352 0.367999 0.127988 -0.132147 0.096902 -0.033046 -0.107276 -0.137927 -0.218263 -0.186941 ... -0.225353 -0.071622 0.014045 0.071194 -0.041501 0.095452 -0.293264 -0.271083 -0.261639 0.331418
75% 0.678227 0.840018 0.803224 0.988846 0.833664 0.708817 0.863212 0.486000 0.360120 0.591453 ... 0.402997 0.572948 0.652250 0.652501 0.642998 0.642986 0.949951 0.249198 0.396105 0.737492
max 1.712359 1.616778 2.124947 1.868353 1.632222 2.036082 1.955072 1.862524 2.218505 1.609443 ... 2.112008 2.537403 2.503715 2.130883 1.704505 1.846445 2.004617 3.413271 1.523123 1.954879

8 rows × 68 columns

In [52]:
columns_idx_inter = pd.Index.intersection(pca_inv_df_cent12.columns,pca_inv_df_cent21.columns)
print("Common columns:", len(columns_idx_inter))
columns_idx_inter
Common columns: 66
Out[52]:
Int64Index([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
            17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
            34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
            51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65],
           dtype='int64')
In [53]:
income_cols = ['FINANZ_MINIMALIST', 'KBA05_ANTG1','PLZ8_ANTG4','HH_EINKOMMEN_SCORE','GREEN_AVANTGARDE']

def col_check(col, col_idx):
    matched_cols = []
    if all(x in list(col_idx) for x in col):
        print("All columns exist")
    else:
        print("One or more column(s) doesn't exist, Matched ones are")
        for x in col:
            if x in list(col_idx):
                print(x)
                
col_check(income_cols,columns_idx_inter)
One or more column(s) doesn't exist, Matched ones are
In [54]:
target_cent_12[income_cols].mean()
Out[54]:
FINANZ_MINIMALIST    -1.244761
KBA05_ANTG1          -1.837937
PLZ8_ANTG4            2.473568
HH_EINKOMMEN_SCORE    1.574395
GREEN_AVANTGARDE     -0.963588
dtype: float64
In [55]:
outside_cent_21[income_cols].mean()
Out[55]:
FINANZ_MINIMALIST     0.098142
KBA05_ANTG1           0.115222
PLZ8_ANTG4           -0.011884
HH_EINKOMMEN_SCORE   -0.089661
GREEN_AVANTGARDE     -0.031000
dtype: float64

Discussion 3.3: Compare Customer Data to Demographics Data

I've chosen finanicial columns to assess the two clusters. It seems that cluster 12 seems to be more finanicial while cluster 21 is not. The finanicial cluster is targeted by the mailing company.